package org.pliers.web.filter;

import org.apache.commons.lang3.StringUtils;
import org.pliers.CommonConstant;
import org.pliers.LbIsolationContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ConditionalOnClass(Filter.class)
public class LbIsolationFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(LbIsolationFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {
        try {
            log.info("LbIsolationFilter doFilterInternal");
            String version = request.getHeader(CommonConstant.VERSION);
            if(StringUtils.isNotEmpty(version)){
                LbIsolationContextHolder.setVersion(version);
            }
            filterChain.doFilter(request, response);
        } finally {
            LbIsolationContextHolder.clear();
        }
    }
}
